import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:fluttermodule/FavListTitle.dart';
import 'package:fluttermodule/view/AppNavi.dart';
import 'color/MyColor.dart';
import 'dart:io';
import 'model/Classify.dart';
import 'color/MyNetTool.dart';
import 'package:flutter_section_table_view/flutter_section_table_view.dart';
import 'package:flutter/services.dart';

class More extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
      ),
      home:MoreCtrl(title: "",),
    );
  }
}

class MoreCtrl extends StatefulWidget{
  MoreCtrl({Key key, this.title,this.major,this.gender}) : super(key: key);
  String title;
  String major;
  String gender;
  @override
  State<StatefulWidget> createState() {
    return _MoreCtrlState();
  }
}
class _MoreCtrlState extends State<MoreCtrl> {
  //Flutter向iOS发送数据
  static const methodChannel = const MethodChannel('com.pages.method/detail');
  //接收iOS向Flutter发送过来的数据
  static const eventChannel = const EventChannel('com.pages.event/detail');

  final refreshController = RefreshController();
  var page     = 1;
  var listData = <Books>[];
  String emptyToast  = "数据加载中...";
  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
    print("deactivate");
  }
  void dispose() {
    super.dispose();
    print('--------dispose---------');
  }
  void initState(){
    super.initState();
    eventChannel.receiveBroadcastStream(1).listen(onEvent,onError: onError);

    loadData();
  }
  void onError(Object error) {
    print(error.toString());
  }
  void onEvent(Object event) {
    Map map = event;
    String major =  map["major"].toString();
    widget.major = major;
    String title =  map["gender"].toString();
    widget.gender = title;
    widget.title = major;
    loadData();
  }
    void loadData() async{
    Map<String, dynamic> params = {"gender":widget.gender,"major":widget.major,"type":"hot","minor":"","start":page,"limit":40};
    Map map =  await MyNetTool.method(HttpMethod.Get, AppBaseUrl1, "/book/by-categories", params, null);
    ClassifyItem item = ClassifyItem.fromJson(map);
    this.listData.addAll(item.books);
    refreshController.sendBack(page == 1 ? true : false, RefreshStatus.completed);
    if (item.books.length > 0){
      page = page + 1;
    }
    this.listData.length > 0 ? reloadData() : emptyData();

  }
  void reloadData(){
    this.emptyToast = "";
    setState(() {

    });
  }
  void emptyData(){
    this.emptyToast = "数据空空如也...";
    setState(() {
    });
  }
  void getDataTool(String url,String txCode,Map params) async{
    try{
      var paramurl = MyUrl.getUrlForMap(params);
      var stringUrl = url + txCode + paramurl;
      //创建一个HttpClient
      HttpClient httpClient = new HttpClient();
      //打开Http连接
      var request = await httpClient.getUrl(Uri.parse(stringUrl));
      httpClient.connectionTimeout = Duration(seconds: 10);
      request.headers.add("Content-Type", "application/json");
      request.headers.add("Accept", "application/json, text/plain, */*");
      var response = await request.close();
      String responseBody = await response.transform(Utf8Codec().decoder).join();

      Map<String ,dynamic> map = json.decode(responseBody);
      ClassifyItem item = ClassifyItem.fromJson(map);
      this.listData.addAll(item.books);
      this.emptyToast = this.listData.length > 0 ? "" :"数据空空如也...";
      setState(() {

      });
    }catch (e){
      print("请求失败：$e");
      this.emptyToast = "数据请求失败...";
    }finally{

    }
  }
  Indicator refreshHeaderBuilder(BuildContext context, int mode) {
    return ClassicIndicator(
      mode: mode,
      releaseText: '释放以刷新',
      refreshingText: '刷新中...',
      completeText: '完成',
      failedText: '失败',
      idleText: '下拉以刷新',
      noDataText: '数据空空如也...',
    );
  }
  Indicator refreshFooterBuilder(BuildContext context, int mode) {
    return ClassicIndicator(
      mode: mode,
      releaseText: '释放以加载',
      refreshingText: '加载中...',
      completeText: '加载完成',
      failedText: '加载失败',
      idleText: '上拉以加载',
      noDataText: '数据空空如也...',
      idleIcon: const Icon(Icons.arrow_upward, color: Colors.grey),
      releaseIcon: const Icon(Icons.arrow_downward, color: Colors.grey),
    );
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.init(context,width: 750/2,height: 1334/2);
    var height =  AppHeigh - AppStatusBar - AppNaviBar;
    var width = AppWidth;
    return Scaffold(
      appBar: AppNavi(
        title: widget.title,
        backgroundColor: MyColor.AppColor,
        textColor: MyColor.AppFFFFFF,
        onPressed:(){
          methodChannel.invokeMethod('back',null);
          Navigator.of(context).pop();
        },
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            new Container(
              width: AppWidth,
              height: height,
              child: Stack(
                children: <Widget>[
                  new Container(
                    child: SectionTableView(
                      refreshHeaderBuilder: refreshHeaderBuilder,
                      refreshFooterBuilder:refreshFooterBuilder,
                      enablePullDown: true,
                      enablePullUp: this.listData.length > 10 ? true : false,
                      onRefresh: (bool up) {
                        if (up == true) {
                          page = 1;
                        }
                        loadData();
                      },
                      refreshController: refreshController,
                      sectionCount: 1,
                      numOfRowInSection: (section){
                        return this.listData.length;
                      },
//                      headerInSection: (section){
//                        return Container(
//                          margin: EdgeInsets.only(top: 6),
//                          height: 25.0,
//                          color: Colors.grey,
//                          child: Text('Header $section',textAlign: TextAlign.center,),
//                        );
//                      },
                      divider: Container(
                        color: MyColor.AppColor,
                        height: 0.70,
                      ),
                      cellAtIndexPath: (section,row){
                        Books male = this.listData[row];
                        var url = male.cover;
                        return ItemTitle(title: male.title,subTitle: male.shortIntro ,url: MyUrl.getNewUrl(url),nickName: male.author,lastChapter:male.lastChapter,onTap: (){
                          methodChannel.invokeMethod('detail',{"bookId":male.sId});
                        },);
                      },
                    ),
                  ),
                  new Container(
                    margin: EdgeInsets.only(top:height/2-40,left:width/2-50),
                    child: Text(emptyToast,textAlign: TextAlign.center,style:TextStyle(
                      color: MyColor.AppColor,
                      fontSize: 18,
                    ),),
                  ),
                ],
              ),

            ),
          ],
        ),
      ),
    );
  }
}